#include "ndk/file_io.h"

namespace ndk
{
file_io::file_io()
{
  init(0);
}
file_io::file_io(const char *filename)
{
  init(filename);
}
void file_io::init(const char *filename)
{
  if (this->file_name_) delete []this->file_name_;
  this->file_name_ = 0;
  this->file_handle_ = NDK_INVALID_HANDLE;
  if (filename)
  {
    int l = ::strlen(filename);
    this->file_name_ = new char[l + 1];
    ::strcpy(this->file_name_, filename);
    this->file_name_[l] = '\0';
  }
}
file_io::~file_io()
{
  if (this->file_name_)
    delete []this->file_name_;
  this->file_name_ = 0;
  this->close();
}
int file_io::open(const char *filename, int flags)
{
  this->init(filename);
  return this->open(flags);
}
int file_io::open(int flags)
{
  if (this->file_name_ == 0) return -1;
  this->file_handle_ = ndk_os::open(this->file_name_, flags);
  return this->file_handle_ == NDK_INVALID_HANDLE ? -1 : 0;
}
int file_io::close()
{
  if (this->file_handle_ != NDK_INVALID_HANDLE)
    ndk_os::close(this->file_handle_);
  this->file_handle_ = NDK_INVALID_HANDLE;
}
long long file_io::size()
{
  ndk_stat st;
  ::memset(&st, 0, sizeof(st));
  if (ndk_os::stat(this->file_name_, &st) == 0)
  {
    return st.st_size;
  }
  return -1;
}
} // namespace ndk

